<template>
  <div
    style="
      display: flex;
      justify-content: center;
      align-items: flex-start;
      flex-direction: column;
      padding: 20px;
    "
  >
    <!-- 基础信息 -->
    <el-card style="width: 75vw; padding: 20px; margin-bottom: 20px">
      <div class="title">基础信息</div>
      <el-form :model="form.supplier" label-width="150px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="登录账号：">
              <el-input v-model="form.supplier.account" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码：">
              <el-input
                v-model="form.supplier.password"
                placeholder="请输入"
                type="password"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="供应商公司名称：">
              <el-input v-model="form.supplier.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地区：">
              <el-input v-model="form.supplier.area" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="地址：">
              <el-input v-model="form.supplier.address" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司简介：">
              <el-input v-model="form.supplier.desc" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <!-- 树形下拉框选择 -->
          <el-col :span="12">
            <el-form-item label="主营产品分类：">
              <el-tree-select
                v-model="form.supplier.fication"
                :data="categories"
                :render-after-expand="false"
                style="width: 100%"
                placeholder="请选择"
                :props="{
                  label: 'label',
                  value: 'value',
                  children: 'children'
                }"
                multiple
                clearable
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="报价系数：">
              <el-input v-model="form.supplier.quotation" placeholder="15%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="可以生产的材料种类：">
          <el-checkbox-group v-model="form.supplier.type">
            <el-checkbox :value="'mn13cr2'">Mn13Cr2</el-checkbox>
            <el-checkbox :value="'mn18cr2'">Mn18Cr2</el-checkbox>
            <el-checkbox :value="'mn22cr2'">Mn22Cr2</el-checkbox>
            <el-checkbox :value="'metal12'"
              >高碳高耐磨合金钢加陶瓷(合金12#)</el-checkbox
            >
            <el-checkbox :value="'cr26'">高碳高耐磨Cr26加陶瓷</el-checkbox>
            <el-checkbox :value="'metal11'"
              >低碳耐磨合金钢加陶瓷(合金钢11#)</el-checkbox
            >
            <el-checkbox :value="'cr26Add'">低碳耐磨Cr26加陶瓷</el-checkbox>
            <el-checkbox :value="'cr28Add'">高碳高耐磨Cr28加陶瓷</el-checkbox>
            <el-checkbox :value="'alloyed'">合金钢</el-checkbox>
            <el-checkbox :value="'highCr26'">高碳高耐磨Cr26</el-checkbox>
            <el-checkbox :value="'kmt'">高铬铸铁KmTBCr26Mo0.5</el-checkbox>
            <el-checkbox :value="'hhras'">高碳高耐磨合金镜</el-checkbox>
            <el-checkbox :value="'tic'">TiC材质</el-checkbox>
            <el-checkbox :value="'eightGrade'">8.8级</el-checkbox>
            <el-checkbox :value="'tenGrade'">10.9级</el-checkbox>
            <el-checkbox :value="'twelveGrade'">12.9级</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-row :gutter="10">
          <!-- 修改为上传执照 -->
          <el-form-item label="上传执照：" prop="form.supplier.license">
            <el-upload
              class="avatar-uploader"
              :action="host + '/upload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item label="上传logo：">
            <el-upload
              class="avatar-uploader"
              :action="host + '/upload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccessLogo"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl2" :src="imageUrl2" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-row>
      </el-form>
    </el-card>

    <!-- 联系人信息 -->
    <el-card style="width: 75vw; padding: 20px; margin-bottom: 20px">
      <div class="title">联系人信息</div>
      <el-form :model="form.supplierContact" label-width="150px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="预售联系人：">
              <el-input
                v-model="form.supplierContact.contactName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预售联系电话：">
              <el-input
                v-model="form.supplierContact.saleNumber"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="销售邮箱：">
              <el-input
                v-model="form.supplierContact.saleEmail"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="老板联系人：">
              <el-input
                v-model="form.supplierContact.bossContact"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="老板联系电话：">
              <el-input
                v-model="form.supplierContact.bossNumber"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="老板邮箱：">
              <el-input
                v-model="form.supplierContact.bossEmail"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="财务联系人：">
              <el-input
                v-model="form.supplierContact.finaContact"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="财务联系电话：">
              <el-input
                v-model="form.supplierContact.finaNumber"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="12">
          <el-form-item label="财务邮箱：">
            <el-input
              v-model="form.supplierContact.finaEmail"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-form>
    </el-card>

    <!-- 收付款信息 -->
    <el-card style="width: 75vw; padding: 20px; margin-bottom: 20px">
      <div class="title">收付款信息</div>
      <el-form :model="form.payment" label-width="150px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="开户银行：">
              <el-input v-model="form.payment.bank" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收款账号：">
              <el-input
                v-model="form.payment.creditAccount"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 开票信息 -->
    <el-card style="width: 75vw; padding: 20px; margin-bottom: 20px">
      <div class="title">开票信息</div>
      <el-form :model="form.payment" label-width="150px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="公司名称：">
              <el-input
                v-model="form.payment.companyName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纳税识别号：">
              <el-input
                v-model="form.payment.taxIdentify"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="备注：">
              <el-input v-model="form.payment.remark" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 运费条款 -->
    <el-card style="width: 75vw; padding: 20px; margin-bottom: 20px">
      <div class="title">运费条款</div>
      <div class="mb-2 ml-4">
        <span>是否含运费：</span>
        <el-radio-group v-model="radio1">
          <el-radio value="1" size="large">是</el-radio>
          <el-radio value="2" size="large">否</el-radio>
        </el-radio-group>
      </div>
      <div class="my-2 ml-4">
        <span>是否含进仓费：</span>
        <el-radio-group v-model="radio2">
          <el-radio value="1">是</el-radio>
          <el-radio value="2">否</el-radio>
        </el-radio-group>
      </div>
      <div class="my-3 ml-4">
        <span>产品参数支持：</span>
        <el-radio-group v-model="radio3">
          <el-radio value="1">需要审核</el-radio>
          <el-radio value="2">无需审核</el-radio>
        </el-radio-group>
      </div>
    </el-card>
    <!-- 按钮保持在最底部 -->
    <div style="flex-grow: 1"></div>
    <el-form-item style="text-align: center">
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button>取消</el-button>
    </el-form-item>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { saveSupplierBasic, getCategoryList } from "@/api/supplier/supplier";
import host from "@/utils/env.js";

const form = reactive({
  // 基础信息、传递了account和password
  supplier: {
    account: "",
    password: "",
    name: "",
    area: "",
    address: "",
    desc: "",
    fication: "",
    quotation: "",
    type: [], // 用于存储选中的材料种类，数组
    licence: "", // 上传执照
    logo: "" // 上传logo
  },
  // 联系人信息
  supplierContact: {
    contactName: "",
    saleNumber: "",
    saleEmail: "",
    bossContact: "",
    bossNumber: "",
    bossEmail: "",
    finaContact: "",
    finaNumber: "",
    finaEmail: ""
  },
  // 收付款信息
  payment: {
    bank: "",
    creditAccount: "",
    companyName: "",
    taxIdentify: "",
    remark: "",
    ischarge: "1",
    isentrance: "1",
    issupport: "1"
  }
});
// 图片地址
const imageUrl = ref("");
const imageUrl2 = ref("");
// 运费条款单选框
const radio1 = ref("1");
const radio2 = ref("1");
const radio3 = ref("1");
// 从后端获取的产品分类数据,树形选择下拉列表
const categories = ref<
  Array<{ label: string; value: string; children?: any[] }>
>([]);

// 获取分类数据的方法
const fetchCategories = async () => {
  try {
    const params = {
      page: 1, // 请求第一页的数据
      pageSize: 10 // 每页请求10条数据
    };

    // 获取分类数据
    const response = await getCategoryList(params);

    if (response.code === 200) {
      const categoriesData = response.data.data;

      // 创建一个对象，用来保存所有的分类，key 为分类的 code，value 为分类对象
      const categoryMap = new Map<
        string,
        { label: string; value: string; children: any[] }
      >();

      // 遍历所有分类数据并添加到 map 中
      categoriesData.forEach((category: any) => {
        const code = category.code.toString(); // 分类的唯一标识，转为字符串处理
        const label = category.type_name; // 分类名称

        // 为每个分类创建一个对象，并设置 label, value 和 children 属性
        if (!categoryMap.has(code)) {
          categoryMap.set(code, {
            label,
            value: code,
            children: [] // 用来存储子类
          });
        }
      });

      // 建立父子关系
      categoriesData.forEach((category: any) => {
        const code = category.code.toString(); // 当前分类的 code
        const parentCode = category.pid.toString(); // 当前分类的父类的 code

        // 如果当前分类有父类，并且父类存在于 map 中，则将当前分类添加到父类的 children 中
        if (parentCode !== "1" && categoryMap.has(parentCode)) {
          categoryMap.get(parentCode)?.children.push(categoryMap.get(code));
        }
      });

      // 最终的分类列表是所有一级分类（即 code 长度为 2 的分类）
      categories.value = Array.from(categoryMap.values()).filter(
        (category: any) => category.value.length === 2
      );
    } else {
      ElMessage.error("加载分类失败");
    }
  } catch (error) {
    ElMessage.error("获取分类数据出错");
    console.error(error); // 打印具体的错误信息
  }
};

// 组件挂载时调用fetchCategories方法
onMounted(() => {
  fetchCategories();
});

// 上传前
const beforeAvatarUpload = (rawFile: any) => {
  if (rawFile.type !== "image/png") {
    ElMessage.error("执照图片必须为 PNG 格式！");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("执照图片大小不能超过 10MB！");
    return false;
  }
  return true;
};

//上传成功
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code == 200) {
    //显示图片
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
    //更改图片地址
    form.supplier.licence = response.data;
    ElMessage.success("上传成功");
  }
};

const handleAvatarSuccessLogo = (response, uploadFile) => {
  if (response.code == 200) {
    //显示图片
    imageUrl2.value = URL.createObjectURL(uploadFile.raw);
    //更改图片地址
    form.supplier.logo = response.data;
    ElMessage.success("上传成功");
  }
};

// 提交表单,使用saveSupplierBasic传递整个大参数
const onSubmit = async () => {
  // 处理 type 数组，将选中的值转换为 { 材料名称: 1 }
  const processedType = {};
  form.supplier.type.forEach(item => {
    processedType[item] = 1; // 选中的值赋值为 1
  });

  // 复制表单数据，并去掉 `type`
  const supplierData = { ...form.supplier, ...processedType };
  Reflect.deleteProperty(supplierData, "type"); // 彻底删除 type

  // 处理运费条款
  const freightTerms = {
    ischarge: radio1.value === "1" ? 1 : 0, // 是否含运费
    isentrance: radio2.value === "1" ? 1 : 0, // 是否含进仓费
    issupport: radio3.value === "1" ? 1 : 0 // 产品参数支持
  };

  // 处理收付款信息，并合并运费条款
  const paymentData = {
    ...form.payment,
    ...freightTerms // 合并运费条款
  };

  // 处理 fication 字段，确保后端能够正确接收
  const ficationData = Array.isArray(form.supplier.fication)
    ? form.supplier.fication.join(",") // 如果是数组，使用 join 转换为字符串
    : form.supplier.fication || ""; // 如果不是数组，直接使用原始值或者空字符串

  const submitData = JSON.parse(
    JSON.stringify({
      ...form,
      supplier: { ...supplierData, fication: ficationData }, // 深拷贝,彻底去除type，处理fication
      payment: paymentData // 确保 payment 数据包含运费条款
    })
  );

  // 表单信息提交
  try {
    await saveSupplierBasic(submitData);
    ElMessage.success("供应商信息保存成功！");
  } catch (error) {
    ElMessage.error("保存失败，请检查输入！");
  }
};
</script>

<style scoped>
.title {
  margin-top: -40px;
  margin-bottom: 40px;
  margin-left: -40px;
  text-align: center;
  padding: 10px 0;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  width: 1030px;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  background-color: #ff7a7a7a;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
